//
//  XHPhotographyHelper.m
//  MessageDisplayExample
//
//  Created by HUAJIE-1 on 14-5-3.
//  Copyright (c) 2014年 曾宪华 开发团队(http://iyilunba.com ) 本人QQ:543413507 本人QQ群（142557668）. All rights reserved.
//

#import "XHPhotographyHelper.h"
#import "XHMacro.h"
//#import <AVFoundation/AVFoundation.h>
@interface XHPhotographyHelper () <UINavigationControllerDelegate, UIImagePickerControllerDelegate>

@property (nonatomic, copy) DidFinishTakeMediaCompledBlock didFinishTakeMediaCompled;

@end

@implementation XHPhotographyHelper

- (instancetype)init {
    self = [super init];
    if (self) {
    }
    return self;
}

- (void)dealloc {
    self.didFinishTakeMediaCompled = nil;
}

- (void)showOnPickerViewControllerSourceType:(UIImagePickerControllerSourceType)sourceType onViewController:(UIViewController *)viewController compled:(DidFinishTakeMediaCompledBlock)compled {
    if (![UIImagePickerController isSourceTypeAvailable:sourceType]) {
        compled(nil, nil);
        return;
    }
    self.didFinishTakeMediaCompled = [compled copy];
    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.editing = YES;
    imagePickerController.delegate = self;
    imagePickerController.sourceType = sourceType;
    imagePickerController.videoMaximumDuration = 30.0f;
//    imagePickerController.videoQuality = UIImagePickerControllerQualityTypeHigh;
    if (sourceType == UIImagePickerControllerSourceTypeCamera) {
        imagePickerController.mediaTypes =  [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];
    }else {
        imagePickerController.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:sourceType];
    
    }
    [viewController presentViewController:imagePickerController animated:YES completion:NULL];
}

- (void)dismissPickerViewController:(UIImagePickerController *)picker {
    WEAKSELF
    [picker dismissViewControllerAnimated:YES completion:^{
        weakSelf.didFinishTakeMediaCompled = nil;
    }];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo {
    if (self.didFinishTakeMediaCompled) {
        self.didFinishTakeMediaCompled(image, editingInfo);
    }
    [self dismissPickerViewController:picker];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    if (self.didFinishTakeMediaCompled) {
        //NSMutableDictionary *muDict = [info mutableCopy];
//        if ([info[UIImagePickerControllerMediaType] isEqualToString:@"public.movie"]) {
//            
//            NSString *videoURL = [NSString stringWithFormat:@"%@",info[UIImagePickerControllerMediaURL]];
//            NSLog(@"%@",[NSString stringWithFormat:@"%ld MB", (long)[self getFileSize:[videoURL substringFromIndex:16]]]);
//            NSURL *mp4Url = [self revoverToMp4WithPathUrl:info[UIImagePickerControllerMediaURL]];
//            [muDict setObject:mp4Url forKey:UIImagePickerControllerMediaURL];
//            if ([[muDict allKeys] count] == 2) {
//                NSFileManager *filemanager = [[NSFileManager alloc]init];
//                if([filemanager fileExistsAtPath:videoURL]){
//                    NSError *error;
//                    [filemanager removeItemAtPath:videoURL error:&error];
//                }
//            }
//        }
        self.didFinishTakeMediaCompled(nil, info);
        
    }
    [self dismissPickerViewController:picker];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [self dismissPickerViewController:picker];
}
//获取视频 大小
- (NSInteger) getFileSize:(NSString*) path
{
    NSFileManager * filemanager = [[NSFileManager alloc]init];
    if([filemanager fileExistsAtPath:path]){
        NSDictionary * attributes = [filemanager attributesOfItemAtPath:path error:nil];
        NSNumber *theFileSize;
        if ( (theFileSize = [attributes objectForKey:NSFileSize]) )
            return  [theFileSize intValue]/1024/1024;
        else
            return -1;
    }
    else
    {
        return -1;
    }
}


//转换格式为 mp4
/*
- (NSURL *)revoverToMp4WithPathUrl:(NSURL *)pathUrl
{
    AVURLAsset *avAsset = [AVURLAsset URLAssetWithURL:pathUrl options:nil];
    NSArray *compatiblePresets = [AVAssetExportSession exportPresetsCompatibleWithAsset:avAsset];
    
    if ([compatiblePresets containsObject:AVAssetExportPresetHighestQuality])
        
    {
        
        
        AVAssetExportSession *exportSession = [[AVAssetExportSession alloc]initWithAsset:avAsset
                                                                              presetName:AVAssetExportPresetHighestQuality];
        NSDateFormatter* formater = [[NSDateFormatter alloc] init];
        [formater setDateFormat:@"yyyy-MM-dd-HH:mm:ss"];
        NSString* _mp4Path = [NSHomeDirectory() stringByAppendingFormat:@"/Documents/output-%@.mp4", [formater stringFromDate:[NSDate date]]];
        NSURL *mp4Url = [NSURL URLWithString:_mp4Path];
        exportSession.outputURL = [NSURL fileURLWithPath: _mp4Path];
        exportSession.shouldOptimizeForNetworkUse = YES;
        exportSession.outputFileType = AVFileTypeMPEG4;
        [exportSession exportAsynchronouslyWithCompletionHandler:^{
            switch ([exportSession status]) {
                case AVAssetExportSessionStatusFailed:
                {
                    UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Error"
                        message:[[exportSession error] localizedDescription]
                        delegate:nil
                        cancelButtonTitle:@"OK"
                        otherButtonTitles: nil];
                    [alert show];
                    break;
                }
                    
                case AVAssetExportSessionStatusCancelled:
                    NSLog(@"Export canceled");
                    break;
                case AVAssetExportSessionStatusCompleted:
                    NSLog(@"Successful!");
                    NSLog(@"%@",_mp4Path);
                    NSLog(@"file Size %ldk",(long)[self getFileSize:_mp4Path]);
                    break;
                default:
                    break;
            }
        }];
        return mp4Url;
    }
    else
    {
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Error"
                                                        message:@"AVAsset doesn't support mp4 quality"
                                                       delegate:nil
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles: nil];
        [alert show];
        return nil;
    }
    
    
}
 */

@end
